/**
Company: Sarkar software technologys
WebSite: http://www.sarkar.cn
Author: yeganaaa
Date : 8/2/18
Time: 3:28 PM
 */

package com.ug_project.dict.engine.datatable

import com.ug_project.dict.engine.entity.DictItem
import java.nio.ByteBuffer
import java.nio.channels.SeekableByteChannel

class DataTable(val channel: SeekableByteChannel) {
    private val bytes = ByteArray(1024 * 4)
    private val buffer = ByteBuffer.wrap(bytes)


    fun write(item: DictItem): Int {
        channel.position(channel.size())
        val position = channel.position()
        buffer.clear()
        val keys = item.key.toByteArray()
        val values = item.value.toByteArray()
        buffer.putInt(keys.size)
        buffer.putInt(values.size)
        buffer.put(keys)
        buffer.put(values)
        buffer.flip()
        channel.write(buffer)
        buffer.clear()
        return position.toInt()
    }

    fun read(position: Int): DictItem {
        channel.position(position.toLong())
        buffer.clear()
        channel.read(buffer)
        buffer.flip()
        val keySize = buffer.getInt()
        val valueSize = buffer.getInt()
        val bytesOfKey = ByteArray(keySize)
        val bytesOfValue = ByteArray(valueSize)
        buffer.get(bytesOfKey)
        buffer.get(bytesOfValue)
        return DictItem(String(bytesOfKey), String(bytesOfValue))
    }

    init {
        buffer.put(127)
        buffer.flip()
        channel.write(buffer)
        buffer.clear()
    }
}